package com.jeesite.modules.exam.assessment.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import com.jeesite.autoconfigure.sys.MsgAutoConfiguration;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.sys.entity.*;
import com.jeesite.modules.sys.service.*;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.utils.OfficeUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.assessment.service.DcSupExamInfoService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 考核任务信息表Controller
 * @author xhc
 * @version 2022-05-28
 */
@Controller
@RequestMapping(value = "${adminPath}/exam/dcSupExamInfo")
public class DcSupExamInfoController extends BaseController {

	@Autowired
	private DcSupExamInfoService dcSupExamInfoService;
	@Autowired
	private PostService postService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private SysOfficeUnitService sysOfficeUnitService;

	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private UserService userService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public DcSupExamInfo get(String id, boolean isNewRecord) {
		return dcSupExamInfoService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("exam:dcSupExamInfo:view")
	@RequestMapping(value = {"list", ""})
	public String list(DcSupExamInfo dcSupExamInfo, Model model) {
		model.addAttribute("dcSupExamInfo", dcSupExamInfo);
		Integer currentYear = Integer.parseInt(DateUtils.getYear());
		model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
		model.addAttribute("currentYear", currentYear);
		return "modules/exam/assessment/dcSupExamInfoList";
	}

	/**
	 * quota Collect 指标汇总
	 * @param dcSupExamInfo
	 * @param model
	 * @return
	 */
	@RequiresPermissions("exam:dcSupExamInfo:view")
	@RequestMapping(value = {"listCollect", ""})
	public String listCollect(DcSupExamInfo dcSupExamInfo, Model model) {
		model.addAttribute("dcSupExamInfo", dcSupExamInfo);
		Integer currentYear = Integer.parseInt(DateUtils.getYear());
		model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
		model.addAttribute("currentYear", currentYear);
		return "modules/exam/assessment/dcSupExamInfoListIndex";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("exam:dcSupExamInfo:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<DcSupExamInfo> listData(DcSupExamInfo dcSupExamInfo, HttpServletRequest request, HttpServletResponse response) {
		dcSupExamInfo.setPage(new Page<>(request, response));
		Page<DcSupExamInfo> page = dcSupExamInfoService.findPage(dcSupExamInfo);
		return page;
	}
		/**
		 *  判断流程
		 * @param dcSupExamInfo
		 * @return
		 */
		@RequestMapping(value = "progress")
		@ResponseBody
		public String progress(DcSupExamInfo dcSupExamInfo) {
			String fileStatus =	dcSupExamInfoService.getVersion(dcSupExamInfo);
			if(StringUtils.equals(dcSupExamInfo.getRemarks4(),"4")){
				if( fileStatus!=null){
					return renderResult(Global.TRUE, text("打开成功"));
				}else{
					return renderResult(Global.FALSE, text("打开失败,需要正式单项指标版本发布才可以发送评分通知"));
				}
			}
			if(StringUtils.equals(dcSupExamInfo.getRemarks4(),"5")){
				if(fileStatus!=null ){
					return renderResult(Global.TRUE, text("打开成功"));
				}else{
					return renderResult(Global.FALSE, text("打开失败,需要正式单项指标版本发布才可以发送细则补充通知"));
				}
			}
			return renderResult(Global.TRUE, text("打开成功"));
		}
	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("exam:dcSupExamInfo:view")
	@RequestMapping(value = "form")
	public String form(DcSupExamInfo dcSupExamInfo, Model model,String type) {
		dcSupExamInfo.setCreateDate(dcSupExamInfo.getCreateDate()==null?new Date():dcSupExamInfo.getCreateDate());
		model.addAttribute("dcSupExamInfo", dcSupExamInfo);
		Integer currentYear = Integer.parseInt(DateUtils.getYear());
		model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
		model.addAttribute("currentYear", currentYear);
		model.addAttribute("type",type==null?"0":type);
		return "modules/exam/assessment/dcSupExamInfoForm";
	}


	/**
	 * 保存数据
	 */
	@RequiresPermissions("exam:dcSupExamInfo:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated DcSupExamInfo dcSupExamInfo) {
		if (dcSupExamInfo.getId() !=null){
			dcSupExamInfo.setUpdateDate(new Date());
			dcSupExamInfoService.update(dcSupExamInfo);
		}else{
			dcSupExamInfoService.save(dcSupExamInfo);
		}
		return renderResult(Global.TRUE, text("保存考核任务成功！"));
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("exam:dcSupExamInfo:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(DcSupExamInfo dcSupExamInfo) {
		dcSupExamInfo.setStatus(DcSupExamInfo.STATUS_DISABLE);
		dcSupExamInfoService.updateStatus(dcSupExamInfo);
		return renderResult(Global.TRUE, text("停用考核任务成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("exam:dcSupExamInfo:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(DcSupExamInfo dcSupExamInfo) {
		dcSupExamInfo.setStatus(DcSupExamInfo.STATUS_NORMAL);
		dcSupExamInfoService.updateStatus(dcSupExamInfo);
		return renderResult(Global.TRUE, text("启用考核任务成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("exam:dcSupExamInfo:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(DcSupExamInfo dcSupExamInfo) {
		dcSupExamInfoService.delete(dcSupExamInfo);
		return renderResult(Global.TRUE, text("删除考核任务成功！"));
	}

	/**
	 * 发布
	 */
	@RequiresPermissions("exam:dcSupExamInfo:edit")
	@RequestMapping(value = "publish")
	@ResponseBody
	public String publish(DcSupExamInfo dcSupExamInfo) {
		dcSupExamInfo.setExamStatus(DcSupExamInfo.STATUS_DISABLE);
		dcSupExamInfoService.publish(dcSupExamInfo);
		return renderResult(Global.TRUE, text("考核任务发布成功！"));
	}


	/**
	 * 撤销
	 */
	@RequiresPermissions("exam:dcSupExamInfo:edit")
	@RequestMapping(value = "undo")
	@ResponseBody
	public String undo(DcSupExamInfo dcSupExamInfo) {
		String undo = dcSupExamInfoService.undo(dcSupExamInfo);
		if (undo.equals("error")){
			return renderResult(Global.FALSE, text("该考核任务已有单位接收无法撤销！"));
		}
		return renderResult(Global.TRUE, text("考核任务撤销成功！"));
	}
	@RequiresPermissions("exam:dcSupExamInfo:user")
	@RequestMapping(value = "indexAdmin")
	public String index(EmpUser empUser, Model model) {
		empUser.getEmployee().setOffice(sysOfficeUnitService.getLatestUnitByOffice());
		model.addAttribute("empUser", empUser);
		return "modules/exam/assessment/empUserIndex";
	}
	/**
	 * 二级管理角色
	 */
	@RequiresPermissions("exam:dcSupExamInfo:user")
	@RequestMapping(value = "userList")
	public String indexAdmin(EmpUser empUser, Model model) {
		// 获取角色列表
		Role role = new Role();
		role.setUserType(User.USER_TYPE_EMPLOYEE);
		model.addAttribute("roleList", roleService.findList(role));
		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("empUser", empUser);
		return "modules/exam/assessment/empUserList";
	}
	@Autowired
	private OfficeService officeService;
	@RequiresPermissions("exam:dcSupExamInfo:user")
	@RequestMapping(value = "listUserData")
	@ResponseBody
	public Page<EmpUser> listUserData(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletRequest request, HttpServletResponse response) {
		empUser.getEmployee().getOffice().setIsQueryChildren(true);
		empUser.getEmployee().getCompany().setIsQueryChildren(true);
		empUser.setPage(new Page<>(request, response));
		Office office = empUser.getEmployee().getOffice();
		Office where = new Office();
		where.setStatus(Office.STATUS_NORMAL);
		Office unitOffice  = sysOfficeUnitService.getLatestUnitByOffice();

		Page<EmpUser> page =null;
		if("system".equals(UserUtils.getUser().getUserCode())){
			empUser.getEmployee().setOffice("".equals(office.getOfficeCode())?sysOfficeUnitService.getLatestUnitByOffice():office);
			page = dcSupExamInfoService.findPageCopy(empUser);
		}
		else if(unitOffice != null){

			where.setParentCode(unitOffice.getOfficeCode());
			where.getSqlMap().getWhere().or("office_code", QueryType.EQ,unitOffice.getOfficeCode());
			List<Office> list = officeService.findList(where);
			List<Office> list2 = new ArrayList<>();
			list2.addAll(list);
			for(int i=0 ; i<list.size();i++){
				if("0".equals(list.get(i).getOfficeType())) {
					where.setParentCode(list.get(i).getOfficeCode());
					where.getSqlMap().getWhere().or("office_code", QueryType.EQ, list.get(i).getOfficeCode());
					List<Office> listx = officeService.findList(where);
					list2.addAll(listx);
				}
			}
			List<Office> collect = list2.stream().filter(
					office1 -> StringUtils.equals(StringUtils.isBlank(office.getOfficeCode())?unitOffice.getOfficeCode():office.getOfficeCode(), office1.getOfficeCode())
			).collect(Collectors.toList());
			if(collect!=null && collect.size()>0 ){
				empUser.getEmployee().setOffice("".equals(office.getOfficeCode())?sysOfficeUnitService.getLatestUnitByOffice():office);
				page = dcSupExamInfoService.findPageCopy(empUser);
			}
		}
		page.getList().forEach(x->{x.setMobile(x.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
		x.setLoginCode(x.getLoginCode().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
		});
		return page;
	}

	@RequestMapping(value = "formUser")
	public String formUser(EmpUser empUser, String op, Model model) {
		EmpUser empUser1 = empUserService.get(empUser.getUserCode());
	    Employee employee = empUser1.getEmployee();
		empUser.setEmployee(employee);

		// 设置默认的部门
		if (StringUtils.isBlank(employee.getCompany().getCompanyCode())) {
			employee.setCompany(EmpUtils.getCompany());
		}

		// 设置默认的公司
		if (StringUtils.isBlank(employee.getOffice().getOfficeCode())) {
			employee.setOffice(EmpUtils.getOffice());
		}

		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));

		if (StringUtils.isNotBlank(employee.getEmpCode())){
			// 获取当前用户所拥有的岗位
			employee.setEmployeePostList(employeeService.findEmployeePostList(employee));
			// 获取当前员工关联的附属机构信息
			employee.setEmployeeOfficeList(employeeService.findEmployeeOfficeList(employee));
		}

		// 获取当前编辑用户的角色和权限


			// 获取当前用户所拥有的角色
			Role role = new Role();
			role.setUserCode(empUser.getUserCode());
			model.addAttribute("roleList", roleService.findListByUserCode(role));


		// 操作类型：add: 全部； edit: 编辑； auth: 授权
		model.addAttribute("op", op);
		model.addAttribute("empUser", empUser1);
		return "modules/exam/assessment/empUserForm";
	}

	@RequestMapping({"treeData"})
	@ResponseBody
	public List<Role> treeData() {
		List<Role> roleList = ListUtils.newArrayList();
		Role a = new Role();
		a.setStatus("0");
		a.setUserType("employee");
		roleList =	this.roleService.findList(a);

		return 		roleList.stream().filter(x->StringUtils.inString(x.getRoleCode(),"OTSLEADERESOLVE","SUBAMIND","EL_ORG","OTSTRANSFER","PUBLIC")
		).collect(Collectors.toList());
	}

	@PostMapping(value = "saveUser")
	@ResponseBody
	public String save(@Validated EmpUser empUser, String op, HttpServletRequest request) {
		dcSupExamInfoService.saveRole(empUser);
		return renderResult(Global.TRUE, text("保存角色成功", empUser.getUserName()));
	}

}